package intelligentCustomer.reasoning;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.model.StreamingResponseHandler;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import dev.langchain4j.model.output.Response;
import intelligentCustomer.planning.ReasonGenerator;

/**
 * 推理引擎
 * 负责执行深度推理分析
 */
public class ReasoningEngine {
    private final OpenAiStreamingChatModel model;
    
    public ReasoningEngine(OpenAiStreamingChatModel model) {
        this.model = model;
    }
    
    /**
     * 执行推理
     * 
     * @param input 推理输入
     * @param reasoningType 推理类型
     * @param depth 推理深度
     * @return 推理结果
     */
    public ReasoningResult reason(String input, String reasoningType, int depth) {
        StringBuilder process = new StringBuilder();
        
        // 构建推理提示
        String prompt = buildReasoningPrompt(input, reasoningType, depth);
        
        // 执行推理
        String reasoning = ReasonGenerator.generate(model, prompt);

        // 记录推理过程
        process.append("推理类型: ").append(reasoningType).append("\n");
        process.append("推理深度: ").append(depth).append("\n");
        process.append("推理过程:\n").append(reasoning).append("\n");
        
        // 提取结论
        String conclusion = extractConclusion(reasoning);
        
        return new ReasoningResult(conclusion, process.toString());
    }
    
    /**
     * 构建推理提示
     */
    private String buildReasoningPrompt(String input, String reasoningType, int depth) {
        StringBuilder prompt = new StringBuilder();
        
        prompt.append("请执行以下类型的推理: ").append(reasoningType).append("\n");
        prompt.append("推理深度: ").append(depth).append("\n");
        prompt.append("输入信息:\n").append(input).append("\n\n");
        
        prompt.append("请按照以下步骤进行推理:\n");
        for (int i = 1; i <= depth; i++) {
            prompt.append(i).append(". 推理步骤 ").append(i).append("\n");
        }
        
        prompt.append("\n最后，请提供明确的结论。\n");
        prompt.append("结论: ");
        
        return prompt.toString();
    }
    
    /**
     * 从推理结果中提取结论
     */
    private String extractConclusion(String reasoning) {
        if (reasoning.contains("结论:")) {
            int start = reasoning.lastIndexOf("结论:") + 3;
            return reasoning.substring(start).trim();
        }
        
        // 如果没有明确的结论标记，返回最后一段
        String[] paragraphs = reasoning.split("\n\n");
        if (paragraphs.length > 0) {
            return paragraphs[paragraphs.length - 1].trim();
        }
        
        return reasoning;
    }
} 